;
(function() {
	var sockjs_instance;
	var connection_cache = {};
	var event_cache = {};
	var notify = {
		conns: connection_cache,
		init: function(app) {
			var sockjs = require('sockjs');
			var sockjs_instance = sockjs.createServer();
			setTimeout(function() {
				sockjs_instance.installHandlers(app._server, {
					prefix: '/sock_notify'
				});
				sockjs_instance.on("open", function(conn) {
					console.log("open:", conn);
				});
				sockjs_instance.on('connection', function(conn) {
					if (!conn) {
						return;
					}
					conn.on('data', function(message) {
						var d = domain.create();
						d.on('error', function(e) {
							console.log("--------------------\nSock Error:", String(e), "\n", e.stack, "\n--------------------");
							notify.send(conn, "error", e.message || e);
						});
						d.run(function() {
							// console.log(conn,sockjs_instance);
							try {
								var json_data = JSON.parse(message);
							} catch (e) {
								throwCusError("解析出错");
							}
							notify.emit(json_data.type, conn, json_data.value);
						});
					});
					conn.on('close', function() {
						console.log("close", conn && conn.id);
						notify.emit("close", conn);
					});
				});
			});
		},
		send: function(conn, type, value) {
			if (conn instanceof Array) {
				conn.forEach(function(conn_single) {
					notify.send(conn_single, type, value)
				});
				return;
			}
			// console.log("SOCK SEND:", {
			// 	s_key: conn.s_key,
			// 	s_info: conn.s_info
			// });
			conn.write(JSON._stringify({
				type: type,
				toString: JSON.stringify(value)
			}));
		},
		on: function(eventName, fun) {
			var event_col = event_cache[eventName] || (event_cache[eventName] = []);
			event_col.push(fun);
		},
		emit: function(eventName, conn, value) {
			console.log(event_cache, eventName);
			var event_col = event_cache[eventName];
			console.log("event_col:", event_col);
			if (event_col) {
				event_col.forEach(function(fun) {
					try {
						fun(conn, value)
					} catch (e) {
						notify.send(conn, eventName + "-error", e.message || e);
					}
				});
			}
		}
	}
	module.exports = notify;

	var domain = require("domain");
}());